package com.lsa.letcode.the6.zigzag;

public class Solution {
    public String convert(String s, int nRows) {
    	StringBuilder sb = new StringBuilder();
    	Character[][] buff = zigzag(s, nRows);
    	for (int i = 0; i < buff.length; i++) {
			for (int j = 0; j < buff[i].length; j++) {
				if (buff[i][j] != null) {
					sb.append(buff[i][j]);
				}
			}
		}
        return sb.toString();
    }
    
    public Character[][] zigzag(String s, int nRows) {
    	Character[][] buff;
    	if (nRows == 1) {
    		buff = new Character[nRows][s.length()];
    		for (int i = 0; i < s.length(); i++) {
    			buff[0][i] = s.charAt(i);
			}
    	}
    	else {
    		int nCols = nCols(s, nRows);
        	buff = new Character[nRows][nCols];
        	boolean isDown = true;
        	int r = 0;
        	int c = 0;
        	int i = 0;
        	do
        	{
        		if (isDown) {
        			if (r == nRows) {
        				isDown = false;
        				r -= 2;
        				c++;
        			}
        			else {
        				buff[r++][c] = s.charAt(i++); 
        			}
        		}
        		else {
        			if (r == 0) {
        				isDown = true;
        			}
        			else {
        				buff[r--][c++] = s.charAt(i++);
        			}
        		}
        	}
        	while(i != s.length());
    	}
    	return buff;
    }
    
    public int nCols(String s, int nRows) {
    	int columnNo = 0;
    	boolean isDown = true;
    	int len = s.length();
    	do
    	{
    		if (isDown) {
    			len -= nRows;
    			columnNo++;
    		}
    		else {
    			len -= nRows - 2;
    			columnNo += nRows - 2;
    		}
    		isDown = !isDown;
    	}
    	while(len > 0);
    	
    	return columnNo;
    }
}